package com.fjec.devops.schedule.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjec.common.Const;
import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.DateUtil;
import com.fjec.devops.entity.StatMarketUserNum;
import com.fjec.devops.feign.MarketClient;
import com.fjec.devops.service.IStatMarketUserNumService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class StatShopHandler extends BaseScheduleHandler {

    @Resource
    private MarketClient marketClient;

    @Resource
    private IStatMarketUserNumService statMarketUserNumService;

    public Map<String, Object> handle(int days) {
        Map<String, Object> logMap = new HashMap<>();
        // 处理果农
        String farmerResult;
        try {
            int farmerNum = this.handleFarmer(days);
            farmerResult = String.format("Handle farmer: [%d]", farmerNum);
        } catch (Exception ex) {
            farmerResult = String.format("Handle farmer error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        // 处理分拣厂
        String sortingResult;
        try {
            int sortingNum = this.handleSorting(days);
            sortingResult = String.format("Handle sorting: [%d]", sortingNum);
        } catch (Exception ex) {
            sortingResult = String.format("Handle sorting error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        // 处理农资
        String materialResult;
        try {
            int materialNum = this.handleMaterial(days);
            materialResult = String.format("Handle material: [%d]", materialNum);
        } catch (Exception ex) {
            materialResult = String.format("Handle material error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        // 处理包装厂
        String pkdResult;
        try {
            int pkgNum = this.handlePkg(days);
            pkdResult = String.format("Handle pkg: [%d]", pkgNum);
        } catch (Exception ex) {
            pkdResult = String.format("Handle pkg error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        // 处理采购商
        String purchaseResult;
        try {
            int purchaseNum = this.handlePurchase(days);
            purchaseResult = String.format("Handle purchase: [%d]", purchaseNum);
        } catch (Exception ex) {
            purchaseResult = String.format("Handle purchase error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        logMap.put("farmer", farmerResult);
        logMap.put("sorting", sortingResult);
        logMap.put("material", materialResult);
        logMap.put("pkd", pkdResult);
        logMap.put("purchase", purchaseResult);
        return logMap;
    }

    /**
     * 处理果农
     *
     * @param days
     * @return
     */
    private int handleFarmer(int days) {
        List<Map<String, Object>> resultMapList = marketClient.statFarmerData(days);
        int num = 0;
        Integer busiType = 2;
        for (Map<String, Object> resultMap : resultMapList) {
            String strStatDate = MapUtils.getString(resultMap, "StatDate");
            Integer markCode = MapUtils.getInteger(resultMap, "MarkCode");
            Integer userNum = MapUtils.getInteger(resultMap, "Num");
            LocalDate statDate = DateUtil.parseLd(strStatDate, "yyyy-MM-dd");
            QueryWrapper<StatMarketUserNum> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("StatDate", statDate)
                    .eq("MarkCode", markCode)
                    .eq("BusiType", busiType);
            StatMarketUserNum entity = statMarketUserNumService.getOne(queryWrapper);
            if (entity == null) {
                entity = new StatMarketUserNum();
                entity.setBusiType(busiType);
                entity.setMarkCode(markCode);
                entity.setStatDate(statDate);
                entity.setUserNum(userNum);
                entity.setCreateTime(DateUtil.nowLdt());
            } else {
                entity.setUserNum(userNum);
                entity.setUpdateTime(DateUtil.nowLdt());
            }
            statMarketUserNumService.saveOrUpdate(entity);
            num++;
        }
        return num;
    }

    /**
     * 处理分拣厂
     *
     * @param days
     * @return
     */
    private int handleSorting(int days) {
        List<Map<String, Object>> resultMapList = marketClient.statSortingPlantData(days);
        int num = 0;
        Integer busiType = 3;
        for (Map<String, Object> resultMap : resultMapList) {
            String strStatDate = MapUtils.getString(resultMap, "StatDate");
            Integer markCode = MapUtils.getInteger(resultMap, "MarkCode");
            Integer userNum = MapUtils.getInteger(resultMap, "Num");
            LocalDate statDate = DateUtil.parseLd(strStatDate, "yyyy-MM-dd");
            QueryWrapper<StatMarketUserNum> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("StatDate", statDate)
                    .eq("MarkCode", markCode)
                    .eq("BusiType", busiType);
            StatMarketUserNum entity = statMarketUserNumService.getOne(queryWrapper);
            if (entity == null) {
                entity = new StatMarketUserNum();
                entity.setBusiType(busiType);
                entity.setMarkCode(markCode);
                entity.setStatDate(statDate);
                entity.setUserNum(userNum);
                entity.setCreateTime(DateUtil.nowLdt());
            } else {
                entity.setUserNum(userNum);
                entity.setUpdateTime(DateUtil.nowLdt());
            }
            statMarketUserNumService.saveOrUpdate(entity);
            num++;
        }
        return num;
    }

    /**
     * 处理农资
     *
     * @param days
     * @return
     */
    private int handleMaterial(int days) {
        List<Map<String, Object>> resultMapList = marketClient.statMaterialData(days);
        int num = 0;
        Integer busiType = 4;
        Integer markCode = Const.MARKET_CODE_MATERIAL;
        for (Map<String, Object> resultMap : resultMapList) {
            String strStatDate = MapUtils.getString(resultMap, "StatDate");
            Integer userNum = MapUtils.getInteger(resultMap, "Num");
            LocalDate statDate = DateUtil.parseLd(strStatDate, "yyyy-MM-dd");
            QueryWrapper<StatMarketUserNum> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("StatDate", statDate)
                    .eq("MarkCode", markCode)
                    .eq("BusiType", busiType);
            StatMarketUserNum entity = statMarketUserNumService.getOne(queryWrapper);
            if (entity == null) {
                entity = new StatMarketUserNum();
                entity.setBusiType(busiType);
                entity.setMarkCode(markCode);
                entity.setStatDate(statDate);
                entity.setUserNum(userNum);
                entity.setCreateTime(DateUtil.nowLdt());
            } else {
                entity.setUserNum(userNum);
                entity.setUpdateTime(DateUtil.nowLdt());
            }
            statMarketUserNumService.saveOrUpdate(entity);
            num++;
        }
        return num;
    }

    /**
     * 处理包装厂
     *
     * @param days
     * @return
     */
    private int handlePkg(int days) {
        List<Map<String, Object>> resultMapList = marketClient.statPkgPlantData(days);
        int num = 0;
        Integer busiType = 5;
        for (Map<String, Object> resultMap : resultMapList) {
            String strStatDate = MapUtils.getString(resultMap, "StatDate");
            Integer markCode = MapUtils.getInteger(resultMap, "MarkCode");
            Integer userNum = MapUtils.getInteger(resultMap, "Num");
            LocalDate statDate = DateUtil.parseLd(strStatDate, "yyyy-MM-dd");
            QueryWrapper<StatMarketUserNum> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("StatDate", statDate)
                    .eq("MarkCode", markCode)
                    .eq("BusiType", busiType);
            StatMarketUserNum entity = statMarketUserNumService.getOne(queryWrapper);
            if (entity == null) {
                entity = new StatMarketUserNum();
                entity.setBusiType(busiType);
                entity.setMarkCode(markCode);
                entity.setStatDate(statDate);
                entity.setUserNum(userNum);
                entity.setCreateTime(DateUtil.nowLdt());
            } else {
                entity.setUserNum(userNum);
                entity.setUpdateTime(DateUtil.nowLdt());
            }
            statMarketUserNumService.saveOrUpdate(entity);
            num++;
        }
        return num;
    }

    /**
     * 处理采购商
     *
     * @param days
     * @return
     */
    private int handlePurchase(int days) {
        List<Map<String, Object>> resultMapList = marketClient.statPurchaseData(days);
        int num = 0;
        Integer busiType = 6;
        Integer markCode = Const.MARKET_CODE_PURCHASE;
        for (Map<String, Object> resultMap : resultMapList) {
            String strStatDate = MapUtils.getString(resultMap, "StatDate");
            Integer userNum = MapUtils.getInteger(resultMap, "Num");
            LocalDate statDate = DateUtil.parseLd(strStatDate, "yyyy-MM-dd");
            QueryWrapper<StatMarketUserNum> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("StatDate", statDate)
                    .eq("MarkCode", markCode)
                    .eq("BusiType", busiType);
            StatMarketUserNum entity = statMarketUserNumService.getOne(queryWrapper);
            if (entity == null) {
                entity = new StatMarketUserNum();
                entity.setBusiType(busiType);
                entity.setMarkCode(markCode);
                entity.setStatDate(statDate);
                entity.setUserNum(userNum);
                entity.setCreateTime(DateUtil.nowLdt());
            } else {
                entity.setUserNum(userNum);
                entity.setUpdateTime(DateUtil.nowLdt());
            }
            statMarketUserNumService.saveOrUpdate(entity);
            num++;
        }
        return num;
    }
}
